﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Pathfinding
{
    public class WayPointObject : MonoBehaviour
    {
        public WayPointRoot PointRoot;
        public int ID;
        public int[] DstPoints;
        public Dictionary<int, WayLinkObject> Links = new Dictionary<int, WayLinkObject>();
        
        public void Init(int id,float x = 0,float y = 0)
        {
            gameObject.name = id.ToString();
            transform.localPosition = new Vector3(x,y,0);
            transform.localScale=Vector3.one*0.1f* PointRoot.WayObjectScale;
            this.ID = id;
        }
        public void CheckGenLink()
        {
            if (this.DstPoints == null) return;

            for (int i = 0; i < this.DstPoints.Length; i++)
            {
                if (!this.Links.ContainsKey(this.DstPoints[i]) && this.DstPoints[i] != this.ID)
                {
                    if (PointRoot.GetWayPointById(this.DstPoints[i]))
                    {
                        this.GenLink(this.DstPoints[i]);
                    }
                }
            }
            foreach(KeyValuePair<int,WayLinkObject> linkItem in this.Links)
            {
                bool haveIt  = false;
                for (int i = 0;i<this.DstPoints.Length;i++) 
                {
                    if (this.DstPoints[i] == linkItem.Key) 
                    {
                        haveIt = true;
                    }
                }
                if (!haveIt) 
                {
                    Destroy(linkItem.Value.gameObject);
                    this.Links.Remove(linkItem.Key);
                    return;
                }
            }


        }

        public void GenLink(int dstPointID)
        {

            GameObject newLink = (GameObject)GameObject.Instantiate(Resources.Load("WayLine"));
            newLink.name = this.ID.ToString() + "-" + dstPointID.ToString();
            WayLinkObject linkObject = newLink.AddComponent<WayLinkObject>();
            linkObject.PointRoot = this.PointRoot;
            newLink.transform.parent = transform.parent;
            newLink.transform.localPosition = Vector3.zero;
            linkObject.New(this.ID,dstPointID);
            this.Links.Add(dstPointID, linkObject);
        }
    }
}
/*              __.__
                |   |
 ________.___.__|___|________
 */